package com.jhy.product.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jhy.common.utils.PageUtils;
import com.jhy.common.utils.Query;

import com.jhy.product.dao.CategoryDao;
import com.jhy.product.entity.CategoryEntity;
import com.jhy.product.service.CategoryService;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {


    @Autowired
    CategoryDao categoryDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        //商品所有的分类信息
        List<CategoryEntity> allCategoryEntities = baseMapper.selectList(null);

        //将商品所有的分类信息组装为树形结构
        List<CategoryEntity> level1Menus = allCategoryEntities.stream().filter((categoryEntity) -> {
            //拿到所有的一级分类，即parent_cid==0的分类
            return categoryEntity.getParentCid() == 0;
        }).map((categoryEntity)->{
            //给一级分类设置子分类
            categoryEntity.setChildrens(getChildrens(categoryEntity,allCategoryEntities));
            return categoryEntity;
        }).sorted((menu1,menu2)->{
            //按sort字段进行排序
          return menu1.getSort() == null ? 0 : menu1.getSort() - (menu2.getSort() == null?0:menu2.getSort());
        }).collect(Collectors.toList());

        return level1Menus;
    }


    //递归查找当前分类的所有子分类
    //参数  current:当前分类  allCategoryEntities:商品分类的所有数据
    public List<CategoryEntity> getChildrens(CategoryEntity current,List<CategoryEntity> allCategoryEntities){
        List<CategoryEntity> childrens = allCategoryEntities.stream().filter((categoryEntity) -> {
            //找到当前分类的第一级子分类
            return categoryEntity.getParentCid() == current.getCatId();
        }).map((categoryEntity)->{
            //递归设置子分类
            categoryEntity.setChildrens(getChildrens(categoryEntity,allCategoryEntities));
            return categoryEntity;
        }).sorted((menu1,menu2)->{
            //按sort字段进行排序
            return menu1.getSort() == null ? 0 : menu1.getSort() - (menu2.getSort() == null?0:menu2.getSort());
        }).collect(Collectors.toList());
        return childrens;
    }


    //删除菜单
    @Override
    public void removeMenuByIds(List<Long> asList) {

        //TODO 删除之前需要判断待删除的菜单是否被别的地方引用
        categoryDao.deleteBatchIds(asList);

    }

}